﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace LogViewer
{
   

    public partial class Form1 : Form
    {
        XmlDocument xmlDoc = new XmlDocument();
        
        List<string> log_files_paths;
        BindingSource log_files_path_to_combobox= new BindingSource();
        string current_xml_log_file;


        bool HomePage = true;


        public Form1()
        {
            log_files_paths = new List<string>( Directory.GetFiles(Directory.GetCurrentDirectory(), "*.fw.log", SearchOption.AllDirectories));
            
            
            log_files_path_to_combobox.DataSource=log_files_paths;
            
            Sort_log_files_paths();

            
            InitializeComponent();
            comboBox1.FormattingEnabled = true;
            comboBox1.Format += new ListControlConvertEventHandler(comboBox1_Format);
            comboBox1.DataSource = log_files_path_to_combobox;

            this.LoggersToolStripMenuItem.Enabled = false;
            this.RankToolStripMenuItem.Enabled = false;

            ShowHomePage();
        }



        void comboBox1_Format(object sender, ListControlConvertEventArgs e)
        {
            string temp=(string) e.Value;
            temp = temp.Substring(temp.LastIndexOf('\\')+1);
            temp = temp.Replace('_', ':');
            temp = temp.Remove(temp.Length - 7, 7);
            e.Value = temp;
        }


        void BuildRegisteredLoggersListFromFile(string xml_log_file)
        {
            LoggersToolStripMenuItem.DropDownItems.Clear();

            ToolStripMenuItem all_item = new ToolStripMenuItem("All");
            all_item.Click += new EventHandler(LoggerNameMenuItem_Click);
            LoggersToolStripMenuItem.DropDownItems.Add(all_item);
            
            xmlDoc.Load(xml_log_file);
            XmlNodeList nodes=xmlDoc.SelectNodes("logfile/registered_loggers/logger_name");
            foreach (XmlNode node in nodes)
            {
                ToolStripMenuItem temp=new ToolStripMenuItem(node.InnerText.Trim());
                temp.Click += new EventHandler(LoggerNameMenuItem_Click);
                LoggersToolStripMenuItem.DropDownItems.Add(temp);
            }
        }



        private void OpenOpenFileDialogButton_Click(object sender, EventArgs e)
        {
            DialogResult result=openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                
                if (!log_files_paths.Contains(openFileDialog1.FileName))
                {
                    MessageBox.Show(openFileDialog1.FileName);
                    log_files_paths.Add(openFileDialog1.FileName);
                    Sort_log_files_paths();
                    log_files_path_to_combobox.ResetBindings(true);
                }
            }

        }
        void Sort_log_files_paths()
        {
            log_files_paths.Sort(new Comparison<string>(this.Sort));
        }
        int Sort(string file1, string file2)
        {
            if (File.GetCreationTime(file1) > File.GetCreationTime(file2))
                return -1;
            if (File.GetCreationTime(file1) < File.GetCreationTime(file2))
                return 1;
            return 0;

        }

        private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
        {
            FileInfo a = new FileInfo(log_files_paths[comboBox1.SelectedIndex]);
            //отфильтруем пустые лог-файлы, который образуются при отладке
            //когда программист запустил каркас=>логгер создал лог фаил
            //а затем программист нажал Stop Debugging(Shift+F5)
            //такую ситуацию не отловить и созданный лог-файл останется пустым
            if (a.Length == 0)
            {
                ShowEmptyFilePage();
            }
            else
            {
                ShowHomePage();

                current_xml_log_file = log_files_paths[comboBox1.SelectedIndex];
                BuildRegisteredLoggersListFromFile(current_xml_log_file);

                ShowMainHTMLPage();
                PushNewLogFileToBrowser(current_xml_log_file);
                ((ToolStripMenuItem)this.RankToolStripMenuItem.DropDownItems[0]).Checked = false;
                this.RankToolStripMenuItem.DropDownItems[0].PerformClick();
                ((ToolStripMenuItem)this.LoggersToolStripMenuItem.DropDownItems[0]).Checked = false;
                this.LoggersToolStripMenuItem.DropDownItems[0].PerformClick();
            }
        }

        private void ShowHomePage()
        {
            DirectoryInfo info = new DirectoryInfo(Directory.GetCurrentDirectory());
            OpenWebBrowserWithFile(info.Parent.Parent.FullName + @"\Private\FrameWork\logger_res\HomePage.html");
            //OpenWebBrowserWithFile(@"D:\Documents and Settings\AV\Мои документы\_Projects\__CopInGame_Prototype\_Resource\Private\FrameWork\logger_res\HomePage.html");
            HomePage = true;
        }

        void ShowEmptyFilePage()
        {
            DirectoryInfo info = new DirectoryInfo(Directory.GetCurrentDirectory());
            OpenWebBrowserWithFile(info.Parent.Parent.FullName + @"\Private\FrameWork\logger_res\EmptyFile.html");
            //OpenWebBrowserWithFile(@"D:\Documents and Settings\AV\Мои документы\_Projects\__CopInGame_Prototype\_Resource\Private\FrameWork\logger_res\EmptyFile.html");
        }

        private void ShowMainHTMLPage()
        {
            if (HomePage)
            {
                DirectoryInfo info = new DirectoryInfo(Directory.GetCurrentDirectory());
                OpenWebBrowserWithFile(info.Parent.Parent.FullName + @"\Private\FrameWork\logger_res\MainHTML.html");
                //OpenWebBrowserWithFile(@"D:\Documents and Settings\AV\Мои документы\_Projects\__CopInGame_Prototype\_Resource\Private\FrameWork\logger_res\MainHtml.html");

                this.LoggersToolStripMenuItem.Enabled = true;
                this.RankToolStripMenuItem.Enabled = true;
                HomePage = false;
            }
        }

        #region Работа с браузерным визуальным компонентом
        void OpenWebBrowserWithFile(string file)
        {
            webBrowser1.Navigate(file);
            
            while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
        }

        void PushNewLogFileToBrowser(string filename)
        {
            //webBrowser1.Navigate("javascript:setXmlLogFileName(\"" + filename.Replace("\\","\\\\") + "\");");
            webBrowser1.Document.InvokeScript("setXmlLogFileName", new object[] { filename });
            
        }

        void PushNewMessagePriorityToBrowser(string rank)
        {
            //webBrowser1.Navigate("javascript:setMessagePriority(\"" + rank + "\");");
            webBrowser1.Document.InvokeScript("setMessagePriority", new object[] { rank });
        }

        void PushNewLoggerNameToBrowser(string name)
        {
            //webBrowser1.Navigate("javascript:setNameOfLogger(\"" + name + "\");");
            webBrowser1.Document.InvokeScript("setNameOfLogger", new object[] { name });
        }
        #endregion

        private void MessagePriorityMenuItem_Click(object sender, EventArgs e)
        {
            StringBuilder query = PerformChecking((ToolStripMenuItem)sender);
         
            PushNewMessagePriorityToBrowser(query.ToString());
        }

        private void LoggerNameMenuItem_Click(object sender, EventArgs e)
        {
            StringBuilder query = PerformChecking((ToolStripMenuItem)sender);

            PushNewLoggerNameToBrowser(query.ToString());

        }

        private StringBuilder PerformChecking(ToolStripMenuItem item)
        {
            ToolStripMenuItem all_item = (ToolStripMenuItem)((ToolStripMenuItem)item.OwnerItem).DropDownItems[0];
            StringBuilder query = new StringBuilder();
            if (item.Text == "All")
            {
                all_item.Checked = !all_item.Checked;
                foreach (ToolStripMenuItem _item in ((ToolStripMenuItem)item.OwnerItem).DropDownItems)
                    _item.Checked = all_item.Checked;
                
            }
            else
            {
                all_item.Checked = false;
                item.Checked = !item.Checked;
            }


            foreach (ToolStripMenuItem _item in ((ToolStripMenuItem)item.OwnerItem).DropDownItems)
                if (_item.Checked==true)
                    query.Append(_item.Text);
            return query;
        }



    }

   
}